﻿// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.

#include "tests/cefclient/browser/main_context_impl.h"
#include "tests/cefclient/browser/user_manager.h"

#include "include/cef_parser.h"
#include "include/cef_web_plugin.h"
#include "tests/shared/common/client_switches.h"

#include <conio.h> 
#include <string>
#include <fstream>
#include <streambuf>
#include "protocol.h"
#include <winperf.h>
#include <shlobj.h>
#include <regex>

namespace client {

namespace {

// The default URL to load in a browser window.
//const char kDefaultUrl[] = "http://ss.upupoo.com/people/v2/userInfo.aut?t=1c804a0083f44852a79971a60f76d061";
//const char kDefaultUrl[] = "http://ss.upupoo.com/paper/ws/wallpaper/v3/index.htm";
	const char kDefaultUrl[] = "http://wallpaper.upupoo.com//store/index.htm";
//const char kDefaultUrl[] =  "file:///E://test//testjs//index.html";
// Returns the ARGB value for |color|.
cef_color_t ParseColor(const std::string& color) {
  std::string colorToLower;
  colorToLower.resize(color.size());
  std::transform(color.begin(), color.end(), colorToLower.begin(), ::tolower);

  if (colorToLower == "black")
    return CefColorSetARGB(255, 0, 0, 0);
  else if (colorToLower == "blue")
    return CefColorSetARGB(255, 0, 0, 255);
  else if (colorToLower == "green")
    return CefColorSetARGB(255, 0, 255, 0);
  else if (colorToLower == "red")
    return CefColorSetARGB(255, 255, 0, 0);
  else if (colorToLower == "white")
    return CefColorSetARGB(255, 255, 255, 255);

  // Use the default color.
  return 0;
}

}  // namespace

MainContextImpl::MainContextImpl(CefRefPtr<CefCommandLine> command_line,
	bool terminate_when_all_windows_closed)
	: command_line_(command_line),
	terminate_when_all_windows_closed_(terminate_when_all_windows_closed),
	initialized_(false),
	shutdown_(false),
	background_color_(0),
	browser_background_color_(0),
	caller_hwnd_(0),
	root_hwnd_(0),
	app_model_(AppModel::gallery),
	full_screen_(false),
	screenid_(0),
	dipscale_(1),
	showstatus_(true),
	popup_login_rootwindow_(0),
	new_msg_num_("0"),
	open_msg_("0"),
    use_views_(false) {
  DCHECK(command_line_.get());
  user_token_.clear();
  attachurl_.clear();
  cef_rect_.Set(0,0,0,0);
  // Set the main URL.
  if (command_line_->HasSwitch(switches::kUrl)) {
	  std::string  s = command_line_->GetSwitchValue(switches::kUrl);
	  std::replace(s.begin(), s.end(), '*', ' ');
	  main_url_ = s;
	  if (LOGDEBUG) _cprintf("--url=%s\n", s.c_str());
  }
     
  if (main_url_.empty())
    main_url_ = kDefaultUrl;

  // Whether windowless (off-screen) rendering will be used.
  use_windowless_rendering_ =
      command_line_->HasSwitch(switches::kOffScreenRenderingEnabled);

  // Whether transparent painting is used with windowless rendering.
  const bool use_transparent_painting =
      use_windowless_rendering_ &&
      command_line_->HasSwitch(switches::kTransparentPaintingEnabled);

#if defined(OS_WIN) || defined(OS_LINUX)
  // Whether the Views framework will be used.
  use_views_ = command_line_->HasSwitch(switches::kUseViews);

  if (use_windowless_rendering_ && use_views_) {
    LOG(ERROR)
        << "Windowless rendering is not supported by the Views framework.";
    use_views_ = false;
  }

  if (use_views_ && command_line->HasSwitch(switches::kHideFrame) &&
      !command_line_->HasSwitch(switches::kUrl)) {
    // Use the draggable regions test as the default URL for frameless windows.
    main_url_ = "http://tests/draggable";
  }

  if (command_line->HasSwitch(switches::KShowTop)) {
	  cef_rect_.x = std::stoi(   command_line->GetSwitchValue(switches::KShowLeft).ToString() );
	  cef_rect_.y = std::stoi(command_line->GetSwitchValue(switches::KShowTop).ToString());
	  cef_rect_.width = std::stoi(command_line->GetSwitchValue(switches::KShowWidth).ToString());
	  cef_rect_.height = std::stoi(command_line->GetSwitchValue(switches::KShowHeight).ToString());
	  if (LOGDEBUG)
	      _cprintf("assigned position  %d   %d   %d   %d \n", cef_rect_.x, cef_rect_.y, cef_rect_.width, cef_rect_.height);
  }

  if (command_line->HasSwitch(switches::KCallerHwnd)) {
	  caller_hwnd_  =  (HWND)std::stol(command_line->GetSwitchValue(switches::KCallerHwnd).ToString());
	  if (LOGDEBUG)  _cprintf("assigned caller hwnd  %d  \n", caller_hwnd_);
  }
   
  if (command_line->HasSwitch(switches::KUserToken)) {
	  user_token_ = command_line->GetSwitchValue(switches::KUserToken).ToString();
	  if (LOGDEBUG) _cprintf("assigned token  %s\n ", user_token_.c_str());
  } 
   
  if (command_line->HasSwitch(switches::KJsFile)) {
	  js_file_ = command_line->GetSwitchValue(switches::KJsFile).ToString();
	  if (LOGDEBUG) _cprintf("assigned jsfile  %s\n ", js_file_.c_str());
  }

  if (command_line->HasSwitch(switches::KJsPath)) {
	  std::string s  = command_line->GetSwitchValue(switches::KJsPath).ToString();
	  std::replace(s.begin(), s.end(), '*', ' ');
	  js_directory_ = s;
	  if (LOGDEBUG) _cprintf("assigned js directory  %s\n ",  js_directory_.ToString().c_str());
  }

  if (command_line->HasSwitch(switches::KFirstUrl)) {
	  first_url_ = command_line->GetSwitchValue(switches::KFirstUrl);
	  if (LOGDEBUG) _cprintf("assigned first url directory  %s\n ", first_url_.ToString().c_str());
  }

  if (command_line->HasSwitch(switches::KOpenMsg)) {
	  open_msg_ =  "1";
	  if (LOGDEBUG) _cprintf("has KOpenMsg   \n ");
  }

  if (command_line->HasSwitch(switches::KMsgNum)) {
	  new_msg_num_ = command_line->GetSwitchValue(switches::KMsgNum).ToString();
	  if (new_msg_num_.compare("0") == 0) {
		  open_msg_ = "0";
	  }
	  if (LOGDEBUG) _cprintf("assigned new messages number is  %s\n ", new_msg_num_.c_str());
  }

 

  if (command_line->HasSwitch(switches::KSpeed)) {
	  download_speed_ = atol(command_line->GetSwitchValue(switches::KSpeed).ToString().c_str());
	  if (LOGDEBUG) _cprintf("assigned download speed %d\n ", download_speed_);
  }
   
  if (command_line->HasSwitch(switches::KAttachUrl)) {
	  attachurl_ = command_line->GetSwitchValue(switches::KAttachUrl).ToString();
	  if (LOGDEBUG) _cprintf("assigned attachurl  %s\n ", attachurl_.c_str());
  }

  if (command_line->HasSwitch(switches::KUpupConfig)) {
	  upupoo_config_path_ = command_line->GetSwitchValue(switches::KUpupConfig);
	  std::string s = upupoo_config_path_.ToString();
	  std::replace(s.begin(), s.end(), '*', ' ');
	  upupoo_config_path_.FromString(s);
	  if (LOGDEBUG) _cprintf("assigned upupoo config file path  %s\n ", upupoo_config_path_.ToString().c_str());
  }
  else {
	  TCHAR my_documents[MAX_PATH];
	  SHGetFolderPath(NULL, CSIDL_PERSONAL, NULL, SHGFP_TYPE_CURRENT, my_documents);
	  std::wstring path;  
	  path.append(my_documents).append(L"\\UPUPOO");
	  upupoo_config_path_.FromWString(path);
	  if (LOGDEBUG) _cprintf("pc_client_config.upup  file path  %s\n ", upupoo_config_path_.ToString().c_str());
  }

  if (command_line->HasSwitch(switches::KDetailFlag)) {
	  detail_flag_ = command_line->GetSwitchValue(switches::KDetailFlag);
	  if (LOGDEBUG) _cprintf("assigned detail flag  %s\n ", detail_flag_.ToString().c_str());
  }

  if (command_line->HasSwitch(switches::KWinHide)) {
	  SaveShowStatus(false);
	  if (LOGDEBUG) _cprintf("assigned win hide  \n ");
  }
   
  if (command_line->HasSwitch(switches::KScreenId)) {
	screenid_ = std::stoi (command_line->GetSwitchValue(switches::KScreenId).ToString() );
	if (LOGDEBUG)  _cprintf("assigned screenid_  %d\n ", screenid_);
  }
   
  if (command_line->HasSwitch(switches::KScale)) {
	  dipscale_ = std::stof(command_line->GetSwitchValue(switches::KScale).ToString());
	  if (LOGDEBUG) _cprintf("assigned dpi scale  %f\n ", dipscale_);
  }
   
  if (command_line->HasSwitch(switches::KTabId)) {
	  tabindex_ = std::stoi(command_line->GetSwitchValue(switches::KTabId).ToString());
	  if (LOGDEBUG) _cprintf("assigned tabid_  %d\n ", tabindex_);
  }

  if (command_line->HasSwitch(switches::KVolume)) {
	  volume_ = std::stoi(command_line->GetSwitchValue(switches::KVolume).ToString());
	  if (LOGDEBUG) _cprintf("assigned KVolume  %d\n ", volume_);
  }

  if (command_line->HasSwitch(switches::KPlayModel)) {
	  playmodel_ = std::stoi(command_line->GetSwitchValue(switches::KPlayModel).ToString());
	  if (LOGDEBUG) _cprintf("assigned KPlayModel  %d\n ", playmodel_);
  }
   
  if (command_line->HasSwitch(switches::KWebPage)) {
	  webpage_ = std::stoi(command_line->GetSwitchValue(switches::KWebPage).ToString());
	  if (LOGDEBUG) _cprintf("assigned KWebPage  %d\n ", webpage_);
  }

  if (command_line->HasSwitch(switches::KPlayingId)) {
	  playingid_ = command_line->GetSwitchValue(switches::KPlayingId);
	  if (LOGDEBUG) _cprintf("assigned KPlayingId  %s\n ", playingid_.ToString().c_str());
  }

  full_screen_ = command_line->HasSwitch(switches::KFullScreen);

  if (command_line->HasSwitch(switches::KAppModel)) {
	  app_model_ = std::stoi (command_line->GetSwitchValue(switches::KAppModel).ToString() );
	  if (LOGDEBUG) _cprintf("assigned app_model_  %d\n", app_model_);
	  if (app_model_ == AppModel::capture) {
		  full_screen_ = true;   // this will change full screen model by KFullScreen
	  }
	  else if (app_model_ == AppModel::gallery) {
		  WebUrl  url(main_url_);
		  detail_pid_ = url.Request("pid");
		  if (detail_pid_.empty()) {
			  _cprintf("There is no pid\n");
		  }
		  else {
			  _cprintf("pid %s\n", detail_pid_.ToString().c_str());
		  }
	  }
  }
   
#endif  // defined(OS_WIN) || defined(OS_LINUX)

  if (command_line_->HasSwitch(switches::kBackgroundColor)) {
    // Parse the background color value.
    background_color_ =
        ParseColor(command_line_->GetSwitchValue(switches::kBackgroundColor));
  }

  if (background_color_ == 0 && !use_views_) {
    // Set an explicit background color.
    background_color_ = CefColorSetARGB(255, 255, 255, 255);
  }

  // |browser_background_color_| should remain 0 to enable transparent painting.
  if (!use_transparent_painting) {
    browser_background_color_ = background_color_;
  }

  const std::string& cdm_path =
      command_line_->GetSwitchValue(switches::kWidevineCdmPath);
  if (!cdm_path.empty()) {
    // Register the Widevine CDM at the specified path. See comments in
    // cef_web_plugin.h for details. It's safe to call this method before
    // CefInitialize(), and calling it before CefInitialize() is required on
    // Linux.
    CefRegisterWidevineCdm(cdm_path, NULL);
  }

  if (app_model_ == gallery || app_model_ ==  cinema || app_model_ == login ) {
	  parseAnimateConfig();
	  parseupupooconfig();
  }   

  if (true) {
	  DWORD BufferSize = 1024;
	  DWORD cbData;
	  DWORD dwRet;
	  LONG lResult;
	  HKEY hKey;

	  REGSAM flag = KEY_READ; // | KEY_QUERY_VALUE | KEY_ENUMERATE_SUB_KEYS;
	  lResult = RegOpenKeyEx(HKEY_CURRENT_USER, L"Software\\upupoo", 0, flag, &hKey);
	  if (lResult != ERROR_SUCCESS)
	  {
		  _cprintf("Read paper directory from reg error.\n");
	  }
	  else {
		  PPERF_DATA_BLOCK PerfData = (PPERF_DATA_BLOCK)malloc(BufferSize);
		  if (NULL == PerfData)
		  {
			  _cprintf("Out of memory\n");
		  }
		  else {
			  cbData = BufferSize;
			  dwRet = RegQueryValueEx(hKey,
				  TEXT("installBiZhiDir"),
				  NULL,
				  NULL,
				  (LPBYTE)PerfData,
				  &cbData);

			  if (dwRet == ERROR_SUCCESS) {
				  paper_path.FromWString((LPWCH)PerfData);
				  std::wstring temp = paper_path.ToWString();
				  LPWSTR  end = L"\\";
				  if (temp.back() != *end) {
					  temp.append(L"\\");
				  }
				  paper_path.FromWString(temp);
				  if ( LOGDEBUG) _cwprintf(L"paper directory = [%s]  length = %d\n", paper_path.c_str(), cbData);
			  }
			  else {
				  _cprintf("reg  query paper directory value error %d....\n", dwRet);
			  }
			  free(PerfData);
			  cbData = 128;
			  PPERF_DATA_BLOCK useridata = (PPERF_DATA_BLOCK)malloc(128);
			  dwRet = RegQueryValueEx(hKey,
				  TEXT("LastUserID"),
				  NULL,
				  NULL,
				  (LPBYTE)useridata,
				  &cbData);

			  //if (dwRet == ERROR_SUCCESS) {
				 // std::wstring faviratepath = paper_path.ToWString();
				 // faviratepath.append(L"favirate");
				 // CreateDirectory(faviratepath.c_str(), 0);
				 // faviratepath.append(L"\\");
				 // faviratepath.append((LPWCH)useridata);
				 // CreateDirectory(faviratepath.c_str(), 0);
				 // faviratepath.append(L"\\");
				 // favirate_path_.FromWString(faviratepath); 
				 // if (LOGDEBUG) _cwprintf(L"user favirate path = [%s] \n", favirate_path_.ToWString().c_str());
			  //}
			  //else {
				 // _cprintf("reg  query  userid value error %d....\n", dwRet);
			  //}	
			  free(useridata);
		  }
		  RegCloseKey(hKey);
	  }
  }

  if (LOGDEBUG) _cprintf("MainContextImpl  complete!   \n");

}

MainContextImpl::~MainContextImpl() {
  // The context must either not have been initialized, or it must have also
  // been shut down.
  DCHECK(!initialized_ || shutdown_);
}

std::string MainContextImpl::GetConsoleLogPath() {
  return GetAppWorkingDirectory() + "console.log";
}

std::string MainContextImpl::GetDebugLogPath() {
	return GetAppWorkingDirectory() + "mydebug.log";
}

std::string MainContextImpl::GetMainURL() {
  return main_url_;
}

cef_color_t MainContextImpl::GetBackgroundColor() {
  return background_color_;
}

CefRect  MainContextImpl::GetBound() {
	return cef_rect_;
}

void  MainContextImpl::SaveBoundRect(CefRect & r) {
	cef_rect_ = r;
}

HWND MainContextImpl::GetCallerHwnd() {
	return caller_hwnd_;
}


void MainContextImpl::SaveRootHandler(HWND handler) {
	root_hwnd_ = handler;
}
HWND MainContextImpl::GetRootHandler() {
	return root_hwnd_;
}

void MainContextImpl::SaveLoginPopupHandler(HWND handler) {
	login_popup_hwnd_ = handler;
}
HWND MainContextImpl::GetLoginPopupHandler() {
	return login_popup_hwnd_;
}


//void MainContextImpl::SaveLoginToken(std::string t) {
//	user_token_ = t;
//}
//
//std::string  MainContextImpl::GetLoginToken() {
//	return user_token_;
//}

void MainContextImpl::SaveAppModel(int model) {
	app_model_ = model;
}

int MainContextImpl::GetAppModel() {
	return app_model_;
}

bool MainContextImpl::IsGalleryApp() {
	return  (app_model_ == AppModel::gallery);
}

long MainContextImpl::GetDownloadSpeed() {
	return download_speed_;
}

bool MainContextImpl::IsLoginApp() {
	return  (app_model_ == AppModel::login );
}

bool MainContextImpl::IsUserDetailApp() {
	return  (app_model_ == AppModel::userdetail);
}

bool  MainContextImpl::IsCommentApp() {
	return  (app_model_ == AppModel::comment );
}

bool  MainContextImpl::IsCaptureApp() {
	return  (app_model_ == AppModel::capture);
}

bool  MainContextImpl::IsWebplayerApp() {
	return  (app_model_ == AppModel::webplayer);
}

bool  MainContextImpl::IsAfterSomeApp() {
	return  (app_model_ == AppModel::aftersome );
}

bool  MainContextImpl::IsWidgetApp() {
	return  (app_model_ == AppModel::widget);
}

bool MainContextImpl::IsNewTabApp() {
	return (app_model_ == AppModel::newtab);
}

bool MainContextImpl::IsPaperApp() {
	return (app_model_ == AppModel::paper);
}

bool MainContextImpl::IsCinemaApp() {
	return (app_model_ == AppModel::cinema);
}

bool MainContextImpl::IsUserGuideApp() {
	return (app_model_ == AppModel::userguide);
}

bool MainContextImpl::IsFullScreen() {
	return full_screen_;
}


int MainContextImpl::GetScreenId() {
	return screenid_;
}

std::string MainContextImpl::GetJsFilePath() {
	return js_file_;
}

CefString MainContextImpl::GetJsDirectory() {
	return js_directory_;
}

CefString MainContextImpl::GetFirstUrl() {
	return first_url_;
}
void MainContextImpl::SaveURootUrl(std::string url) {
	urooturl_ = url;
}

std::string MainContextImpl::GetURootUrl() {
	return urooturl_;
}

void MainContextImpl::SaveCommentDetailUrl(std::string url) {
	comment_detail_url_ = url;
}

std::string MainContextImpl::GetCommentDetailUrl() {
	return comment_detail_url_;
}

CefString& MainContextImpl::GetPaperDirectory() {
	return paper_path;
}

std::string  MainContextImpl::GetAttachUrl() {
	return attachurl_;
}

CefString MainContextImpl::GetAnimeDetailFlag() {
	return detail_flag_;
}

float  MainContextImpl::GetDpiScale() {
	return dipscale_;
}

void MainContextImpl::SaveDpiScale(float scale) {
	dipscale_ = scale;
}

void  MainContextImpl::SaveShowStatus(bool status) {
	showstatus_ = status;
}

bool  MainContextImpl::IsShow() {
	return showstatus_;
}

int MainContextImpl::GetTabId() {
	return tabindex_;
}

void MainContextImpl::SaveTabId(int id) {
	tabindex_ = id;
}

void  MainContextImpl::SavePopupType(int type) {
	popup_type_ = type;
}

int  MainContextImpl::GetPopupType() {
	return popup_type_;
}

void MainContextImpl::SavePopupParentWindow(HWND h) {
	popup_login_rootwindow_ = h;
}

HWND MainContextImpl::GetPopupParentWindow() {
	return popup_login_rootwindow_;
	}

bool MainContextImpl::UseViews() {
  return use_views_;
}

bool MainContextImpl::UseWindowlessRendering() {
  return use_windowless_rendering_;
}

void MainContextImpl::PopulateSettings(CefSettings* settings) {
#if defined(OS_WIN)
  settings->multi_threaded_message_loop =
      command_line_->HasSwitch(switches::kMultiThreadedMessageLoop);
#endif

  if (!settings->multi_threaded_message_loop) {
    settings->external_message_pump =
        command_line_->HasSwitch(switches::kExternalMessagePump);
  }

  if (command_line_->HasSwitch(switches::kCachePath)) {
	  std::string s = command_line_->GetSwitchValue(switches::kCachePath).ToString();
	  std::replace(s.begin(), s.end(), '*', ' ');
	  CefString(&settings->cache_path) = s;
	  //command_line_->GetSwitchValue(switches::kCachePath);
  }
  else {
	  if (app_model_ == AppModel::gallery || app_model_ == AppModel::aftersome || app_model_ == AppModel::cinema) {		   
		  CefString(&settings->cache_path) = UserManager::Get()->GetPlayCachePath();
		  if (LOGDEBUG) _cwprintf(L"Set cache path %s  for gallery aftersome cinema\n", UserManager::Get()->GetPlayCachePath().ToWString().c_str());
	  }
	  else {
		  CefString(&settings->cache_path) = UserManager::Get()->GetCachePath();
	  }
  }

  if (use_windowless_rendering_)
    settings->windowless_rendering_enabled = true;

  if (browser_background_color_ != 0)
    settings->background_color = browser_background_color_;
}

void MainContextImpl::PopulateBrowserSettings(CefBrowserSettings* settings) {
  if (command_line_->HasSwitch(switches::kOffScreenFrameRate)) {
    settings->windowless_frame_rate =
        atoi(command_line_->GetSwitchValue(switches::kOffScreenFrameRate)
                 .ToString()
                 .c_str());
  }

  if (browser_background_color_ != 0)
    settings->background_color = browser_background_color_;
}

void MainContextImpl::PopulateOsrSettings(OsrRenderer::Settings* settings) {
  settings->show_update_rect =
      command_line_->HasSwitch(switches::kShowUpdateRect);

  if (browser_background_color_ != 0)
    settings->background_color = browser_background_color_;
}

RootWindowManager* MainContextImpl::GetRootWindowManager() {
  DCHECK(InValidState());
  return root_window_manager_.get();
}

bool MainContextImpl::Initialize(const CefMainArgs& args,
                                 const CefSettings& settings,
                                 CefRefPtr<CefApp> application,
                                 void* windows_sandbox_info) {
  DCHECK(thread_checker_.CalledOnValidThread());
  DCHECK(!initialized_);
  DCHECK(!shutdown_);

  if (!CefInitialize(args, settings, application, windows_sandbox_info))
    return false;

  // Need to create the RootWindowManager after calling CefInitialize because
  // TempWindowX11 uses cef_get_xdisplay().
  root_window_manager_.reset(
      new RootWindowManager(terminate_when_all_windows_closed_));

  initialized_ = true;

  return true;
}

void MainContextImpl::Shutdown() {
  DCHECK(thread_checker_.CalledOnValidThread());
  DCHECK(initialized_);
  DCHECK(!shutdown_);

  root_window_manager_.reset();

  CefShutdown();

  shutdown_ = true;
}


CefString MainContextImpl::GetDetailURL() {
	return   detail_url_;
}

std::string & MainContextImpl::GetDomainUrl() {
	return root_url_;
}

std::string MainContextImpl::GetPageidUrl() {
	return pageid_url_;
}

std::string & MainContextImpl::GetIndexUrl() {
	return index_url_;
}

std::string MainContextImpl::GetCollectionUrl() {
	return collection_url;
}

std::string MainContextImpl::GetBuckUrl() {
	return bucket_url_;
}

std::string MainContextImpl::GetLoginUrl() {
	return login_url_;
}

CefString MainContextImpl::GetFaviratePath() {
	return favirate_path_;
}

int MainContextImpl::GetInitVolume() {
	return volume_;
}

int MainContextImpl::GetInitPlayModel() {
	return playmodel_;
}

int MainContextImpl::GetInitWebPage() {
	return webpage_;
}

CefString MainContextImpl::GetInitPlayingId() {
	return playingid_;
}

std::string MainContextImpl::GetUserUrl() {
	return user_url_;
}

CefString MainContextImpl::GetWinClassName() {
	char  name[64];
	memset(name, '\0', sizeof(name));
	if (IsGalleryApp()) {
		sprintf(name, "cefgallery");
	}
	else if (IsLoginApp()) {
		sprintf(name, "ceflogin");
	}
	else if (IsCommentApp()) {
		sprintf(name, "cefcomment");
	}
	else if (IsCaptureApp()) {
		sprintf(name, "cefcapture");
	}
	else if (IsWebplayerApp()) {
		sprintf(name, "cefwebplayer%d", GetScreenId());
	}
	else if (IsAfterSomeApp()) {
		sprintf(name, "cefaftersome");
	}
	else if (IsWidgetApp()) {
		sprintf(name, "cefwidget");
	}
	else if (IsNewTabApp()) {
		sprintf(name, "cefnewtab");
	}
	else if (IsPaperApp()) {
		sprintf(name, "cefpaper");
	}
	else if (IsUserDetailApp()) {
		sprintf(name, "cefuserdetail");
	}
	else if (IsCinemaApp()) {
		sprintf(name, "cefaftersomeplayweb");
	}
	else if (IsUserGuideApp()) {
		sprintf(name, "userguide");
	}
	else {
		sprintf(name, "CEFCLIENT");
	}

	CefString s(name);
	return s;
}

CefString MainContextImpl::GetAppName() {

	char  name[64];
	memset(name, '\0', sizeof(name));
	if ( IsGalleryApp()) {
		sprintf(name, "gallery");
	}
	else if ( IsLoginApp()) {
		sprintf(name,   "login");
	}
	else if ( IsCommentApp()) {
		sprintf(name,  "comment");
	}
	else if ( IsCaptureApp()) {
		sprintf(name, "capture");
	}
	else if ( IsWebplayerApp()) {
		sprintf(name, "webplayer%d",  GetScreenId());
	}
	else if ( IsAfterSomeApp()) {
		sprintf(name, "aftersome");
	}
	else if ( IsWidgetApp()) {
		sprintf(name, "widget");
	}
	else if ( IsNewTabApp()) {
		sprintf(name, "newtab");
	}
	else if ( IsPaperApp()) {
		sprintf(name, "paper");
	}
	else if ( IsUserDetailApp()) {
		sprintf(name, "userdetail");
	}
	else if (IsCinemaApp()) {
		sprintf(name, "cinema");
	}
	else if (IsUserGuideApp()) {
		sprintf(name, "userguide");
	}

	CefString s(name);
	return s;
}

std::string MainContextImpl::GetAnimateUrl() {
	return animate_url_;
}

std::string  MainContextImpl::GetNewMsgNum() {
	return new_msg_num_;
}

std::string MainContextImpl::GetMsgOpen() {
	return open_msg_;
}

void MainContextImpl::parseupupooconfig() {

	std::wstring domainconfig = upupoo_config_path_.ToWString();
	domainconfig.append(L"\\pc_client_config.upup");
	std::ifstream t(domainconfig);
	if (!t.good()) {
		_cwprintf(L"config file  %s is not exist\n", domainconfig.c_str());
		return;
	}
	std::string str((std::istreambuf_iterator<char>(t)),
		std::istreambuf_iterator<char>());
	t.close();  
	CefString  content;
	content.FromString(str);
	CefRefPtr<CefValue> jsonObject = CefParseJSON(content, JSON_PARSER_ALLOW_TRAILING_COMMAS);
	if (jsonObject !=NULL && jsonObject->IsValid())
	{ 
		CefRefPtr<CefDictionaryValue> dict = jsonObject->GetDictionary();
		CefString page;
		page = dict->GetString("ShowUserInfoURL");
		if ( !page.empty() ) {
			client_identify_.push_back(page);
			if (LOGDEBUG) _cprintf("ShowUserInfoURL is %s\n", page.ToString().c_str());
		}
		page = dict->GetString("DetailURL");
		if (!page.empty()) {
			client_identify_.push_back(page);
			detail_url_ = page;
			if (LOGDEBUG)  _cprintf("DetailURL is %s\n", page.ToString().c_str());
		}
		page = dict->GetString("SearchURL");
		if (!page.empty()) {
			client_identify_.push_back(page);
			if (LOGDEBUG)  _cprintf("SearchURL is %s\n", page.ToString().c_str());
		}
		page = dict->GetString("BrowVIURL");
		if (!page.empty()) {
			client_identify_.push_back(page);
			if (LOGDEBUG)  _cprintf("BrowVIURL is %s\n", page.ToString().c_str());
		}
		page = dict->GetString("FollowURL");
		if (!page.empty()) {
			client_identify_.push_back(page);
			if (LOGDEBUG)  _cprintf("FollowURL is %s\n", page.ToString().c_str());
		}

		page = dict->GetString("IndexURL");
		if (!page.empty()) {
			client_identify_.push_back(page);
			index_url_ = page.ToString();
			if (LOGDEBUG)  _cprintf("IndexURL url is %s\n", page.ToString().c_str());
		}

		page = dict->GetString("LoginURL");
		if (!page.empty()) {
			client_identify_.push_back(page);
			if (LOGDEBUG)  _cprintf("page LoginURL url is %s\n", page.ToString().c_str());
		}
		page = dict->GetString("UserDetailURL");
		if (!page.empty()) {
			client_identify_.push_back(page);
			if (LOGDEBUG)  _cprintf("page UserDetailURL url is %s\n", page.ToString().c_str());
		}
		page = dict->GetString("RootURL");
		if (!page.empty()) {
			//client_identify_.push_back(page);
			root_url_ =  page.ToString();
			if (LOGDEBUG)  _cprintf("RootURL url is %s\n", page.ToString().c_str());
		}

		login_url_ = dict->GetString("ROOTLOGIN").ToString();
		login_url_.append(dict->GetString("LoginURL").ToString());
		if (LOGDEBUG)  _cprintf("login url is %s\n", login_url_.c_str());

		user_url_ = dict->GetString("ROOTLOGIN").ToString();
		user_url_.append(dict->GetString("UserCenter").ToString());
		if (LOGDEBUG)  _cprintf("UserCenter is %s\n", user_url_.c_str());

		page = dict->GetString("PaperIdURL");
		if (!page.empty()) {
			pageid_url_ = page.ToString();
			if (LOGDEBUG)  _cprintf("PaperIdURL url is %s\n", page.ToString().c_str());
		}

		page = dict->GetString("CollectionURL");
		if (!page.empty()) {
			//client_identify_.push_back(page);
			collection_url.append(root_url_);;
			collection_url.append(page.ToString());
			collection_url.append(user_token_);
			collection_url.append(".htm");
			if (LOGDEBUG)  _cprintf("page CollectionURL url is %s\n", collection_url.c_str());
		}
		page = dict->GetString("BucketURL");
		if (!page.empty()) { 
			bucket_url_.append("http://");;
			bucket_url_.append(page.ToString());
			bucket_url_.append("/theme/");
			if (LOGDEBUG)  _cprintf("page BucketURL url is %s\n", bucket_url_.c_str());
		}
	}
	else {
		if (LOGDEBUG)  _cprintf("config fiel is not json format\n");
	}
}

CefString MainContextImpl::GetPidFromUrl() {
	return detail_pid_;
}

void MainContextImpl::ClearPidFromUrl() {
	detail_pid_.clear();
}

void MainContextImpl::parseAnimateConfig() {
	std::wstring animateconfig = upupoo_config_path_.ToWString();
	animateconfig.append(L"\\anime_config.upup");
	std::ifstream t(animateconfig);
	if (!t.good()) {
		_cwprintf(L"config file  %s is not exist\n", animateconfig.c_str());
		return;
	}
	std::string str((std::istreambuf_iterator<char>(t)),
		std::istreambuf_iterator<char>());
	t.close();
	CefString  content;
	content.FromString(str);
	CefRefPtr<CefValue> jsonObject = CefParseJSON(content, JSON_PARSER_ALLOW_TRAILING_COMMAS);
	if (jsonObject != NULL && jsonObject->IsValid())
	{
		CefRefPtr<CefDictionaryValue> dict = jsonObject->GetDictionary();
		std::string  animateroot;
		animateroot = dict->GetString("G_ROOT_URL").ToString();
		animateroot.append(dict->GetString("G_INDEX_URL").ToString());
		if (!animateroot.empty()) {
			animate_url_ = animateroot;
			if (LOGDEBUG)  _cprintf("Animate index url is %s\n", animateroot.c_str());
		}
	}
}

std::vector<CefString> &  MainContextImpl::GetClientIdentify() {
	return client_identify_;
}

std::string WebUrl::Request(const std::string& request) const {
	std::smatch result;	 
	if (std::regex_search(_url.cbegin(), _url.cend(), result, std::regex(request + "=(.*?)&"))) {
		// 匹配具有多个参数的url

		// *? 重复任意次，但尽可能少重复  
		return result[1];
	}
	else if (std::regex_search(_url.cbegin(), _url.cend(), result, std::regex(request + "=(.*)"))) {
		// 匹配只有一个参数的url

		return result[1];
	}
	else {
		// 不含参数或制定参数不存在
		return std::string();
	}
}

}  // namespace client
